package com.cecsmsserve.controller;

import com.cecsmsserve.entity.DiningFeedback;
import com.cecsmsserve.entity.DiningMenu;
import com.cecsmsserve.entity.DiningReview;
import com.cecsmsserve.service.DiningFeedbackService;
import com.cecsmsserve.service.DiningMenuService;
import com.cecsmsserve.service.DiningReviewService;
import com.cecsmsserve.mapper.DiningFeedbackMapper;
import com.cecsmsserve.util.result.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dining")
public class DiningController {
    private static final Logger log = LoggerFactory.getLogger(DiningController.class);
    
    @Autowired
    private DiningReviewService reviewService;
    
    @Autowired
    private DiningFeedbackService feedbackService;
    
    @Autowired
    private DiningMenuService menuService;
    
    @Autowired
    private DiningFeedbackMapper diningFeedbackMapper;

    // 提交评价
    @PostMapping("/review")
    public CommonResult submitReview(@RequestBody DiningReview review) {
        try {
            boolean success = reviewService.submitReview(review);
            return success ? CommonResult.success("提交成功") : CommonResult.failed("提交评价失败");
        } catch (Exception e) {
            log.error("提交评价失败：", e);
            return CommonResult.failed("提交评价失败：" + e.getMessage());
        }
    }

    // 获取订单评价
    @GetMapping("/review/{orderId}")
    public CommonResult getReview(@PathVariable Integer orderId) {
        try {
            DiningReview review = reviewService.getReviewByOrderId(orderId);
            CommonResult result = CommonResult.success(review);
            if (review == null) {
                result.setNotFound();
            }
            return result;
        } catch (Exception e) {
            log.error("获取订单评价失败：", e);
            return CommonResult.failed("获取订单评价失败：" + e.getMessage());
        }
    }

    // 提交需求反馈
    @PostMapping("/feedback")
    public CommonResult<Boolean> submitFeedback(@RequestBody DiningFeedback feedback) {
        boolean success = feedbackService.submitFeedback(feedback);
        return CommonResult.success(success);
    }

    // 管理员回复需求
    @PutMapping("/feedback/reply")
    public CommonResult<Boolean> replyFeedback(@RequestBody Map<String, Object> requestMap) {
        log.info("收到反馈回复请求, 数据: {}", requestMap);
        
        Integer id = (Integer) requestMap.get("id");
        // 尝试从不同字段获取回复内容
        String reply = null;
        if (requestMap.containsKey("reply")) {
            reply = (String) requestMap.get("reply");
        } else if (requestMap.containsKey("admin_reply")) {
            reply = (String) requestMap.get("admin_reply");
        }
        
        log.info("解析后参数: id={}, reply='{}'", id, reply);
        
        if (id == null) {
            log.warn("回复失败: 缺少ID参数");
            return CommonResult.failed("缺少ID参数");
        }
        
        if (reply == null || reply.trim().isEmpty()) {
            log.warn("回复失败: 回复内容为空");
            return CommonResult.failed("回复内容不能为空");
        }
        
        try {
            // 使用原生SQL执行更新
            String sql = "UPDATE dining_feedback SET admin_reply = ?, status = 1, reply_time = NOW() WHERE id = ?";
            log.info("执行SQL: {}, 参数: [{}, {}]", sql, reply, id);
            
            // 使用UpdateWrapper直接更新数据库
            int rows = diningFeedbackMapper.update(
                null,
                new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<DiningFeedback>()
                    .eq("id", id)
                    .set("admin_reply", reply)
                    .set("status", 1)
                    .set("reply_time", new java.util.Date())
            );
            
            log.info("SQL执行结果: 影响行数={}", rows);
            
            if (rows > 0) {
                log.info("回复成功: id={}, 内容='{}'", id, reply);
                return CommonResult.success(true);
            } else {
                log.warn("回复失败: 更新未生效, id={}", id);
                return CommonResult.failed("回复失败，请重试");
            }
        } catch (Exception e) {
            log.error("回复过程中发生异常: {}", e.getMessage(), e);
            return CommonResult.failed("系统错误: " + e.getMessage());
        }
    }

    // 管理员回复需求（新方法 - 应急修复版）
    @PutMapping("/feedback/reply2")
    public CommonResult<Boolean> replyFeedbackFixed(@RequestBody Map<String, Object> requestMap) {
        log.info("========== 开始处理反馈回复请求 ==========");
        log.info("请求数据: {}", requestMap);
        
        Integer id = (Integer) requestMap.get("id");
        String reply = (String) requestMap.get("admin_reply");
        
        log.info("解析后参数: id={}, admin_reply='{}'", id, reply);
        
        if (id == null) {
            log.warn("回复失败: 缺少ID参数");
            return CommonResult.failed("缺少ID参数");
        }
        
        if (reply == null || reply.trim().isEmpty()) {
            log.warn("回复失败: 回复内容为空");
            return CommonResult.failed("回复内容不能为空");
        }
        
        try {
            // 先检查反馈是否存在
            DiningFeedback feedback = feedbackService.getById(id);
            if (feedback == null) {
                log.warn("回复失败: 反馈ID不存在, id={}", id);
                return CommonResult.failed("反馈不存在");
            }
            
            log.info("找到反馈记录: {}", feedback);
            log.info("将执行SQL: UPDATE dining_feedback SET admin_reply='{}', reply_time=NOW(), status=1 WHERE id={}", 
                     reply.replace("'", "''"), id);
            
            // 直接执行Mapper中的方法
            int rows = diningFeedbackMapper.updateReply(id, reply);
            log.info("SQL执行结果: 影响行数={}", rows);
            
            if (rows > 0) {
                // 再次获取反馈记录验证更新结果
                DiningFeedback updated = feedbackService.getById(id);
                log.info("更新后反馈记录: {}", updated);
                log.info("回复成功: id={}, reply='{}'", id, updated.getReply());
                return CommonResult.success(true);
            } else {
                log.warn("回复失败: 数据未更新, id={}", id);
                return CommonResult.failed("回复失败，请确认反馈ID是否存在");
            }
        } catch (Exception e) {
            log.error("回复过程中发生异常: {}", e.getMessage(), e);
            return CommonResult.failed("系统错误: " + e.getMessage());
        } finally {
            log.info("========== 结束处理反馈回复请求 ==========");
        }
    }

    // 获取用户的需求反馈列表
    @GetMapping("/feedback/user")
    public CommonResult<List<DiningFeedback>> getUserFeedbacks(@RequestParam Integer userId) {
        try {
            log.info("获取用户反馈列表，userId: {}", userId);
            List<DiningFeedback> feedbacks = feedbackService.getUserFeedbacks(userId);
            log.info("查询结果：{}", feedbacks);
            return CommonResult.success(feedbacks);
        } catch (Exception e) {
            log.error("获取用户反馈列表失败：", e);
            return CommonResult.failed("获取用户反馈列表失败：" + e.getMessage());
        }
    }

    // 获取未处理的需求反馈列表
    @GetMapping("/feedback/unhandled")
    public CommonResult<List<DiningFeedback>> getUnhandledFeedbacks() {
        try {
            log.info("开始获取未处理反馈列表");
            List<DiningFeedback> feedbacks = feedbackService.getUnhandledFeedbacks();
            log.info("获取未处理反馈列表成功，数量: {}", feedbacks.size());
            return CommonResult.success(feedbacks);
        } catch (Exception e) {
            log.error("获取未处理反馈列表失败：", e);
            return CommonResult.failed("获取未处理反馈列表失败：" + e.getMessage());
        }
    }

    // 获取已处理的需求反馈列表
    @GetMapping("/feedback/handled")
    public CommonResult selectHandled(@RequestParam(defaultValue = "1") Integer pageNum, 
                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            log.info("开始获取已处理反馈列表，页码: {}，每页大小: {}", pageNum, pageSize);
            CommonResult result = feedbackService.selectHandled(pageNum, pageSize);
            log.info("获取已处理反馈列表成功");
            return result;
        } catch (Exception e) {
            log.error("获取已处理反馈列表失败：", e);
            return CommonResult.failed("获取已处理反馈列表失败：" + e.getMessage());
        }
    }

    // 菜单管理相关接口
    @GetMapping("/menu/list")
    public CommonResult getMenuList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String category) {
        return menuService.list(pageNum, pageSize, name, category);
    }

    @PostMapping("/menu")
    public CommonResult addMenu(@RequestBody DiningMenu menu) {
        return menuService.add(menu);
    }

    @PutMapping("/menu/{id}")
    public CommonResult updateMenu(@PathVariable Integer id, @RequestBody DiningMenu menu) {
        menu.setId(id);
        return menuService.update(menu);
    }

    @DeleteMapping("/menu/{id}")
    public CommonResult deleteMenu(@PathVariable Integer id) {
        return menuService.delete(id);
    }

    @PutMapping("/menu/{id}/status")
    public CommonResult updateMenuStatus(
            @PathVariable Integer id,
            @RequestBody DiningMenu menu) {
        return menuService.updateStatus(id, menu.getStatus());
    }

    // 直接执行SQL更新反馈回复（紧急修复接口）
    @PutMapping("/feedback/fix")
    public CommonResult<Boolean> fixFeedbackReply(@RequestBody Map<String, Object> requestMap) {
        Integer id = (Integer) requestMap.get("id");
        String reply = (String) requestMap.get("admin_reply");
        
        log.info("收到紧急修复请求: id={}, admin_reply='{}'", id, reply);
        
        if (id == null || reply == null) {
            return CommonResult.failed("参数错误");
        }
        
        // 使用更简单的方法 - 直接执行SQL更新
        try {
            // 使用UpdateWrapper更新字段
            int rows = diningFeedbackMapper.update(
                null,
                new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<DiningFeedback>()
                    .eq("id", id)
                    .set("admin_reply", reply)
                    .set("status", 1)
                    .set("reply_time", new java.util.Date())
            );
            
            log.info("SQL更新结果：影响行数={}", rows);
            
            if (rows > 0) {
                return CommonResult.success(true);
            } else {
                log.warn("回复失败：数据未更新");
                return CommonResult.failed("回复失败，请重试");
            }
        } catch (Exception e) {
            log.error("修复过程中发生异常: {}", e.getMessage(), e);
            return CommonResult.failed("修复失败: " + e.getMessage());
        }
    }
} 